package com.mall.shopping.services.Goods;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.shopping.IGoodsQueryServcice;
import com.mall.shopping.converter.GoodsSortByPageConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.GoodsSortDto;
import com.mall.shopping.dto.ShowGoodsByPageRequest;
import com.mall.shopping.dto.ShowGoodsByPageResponse;
import org.apache.dubbo.config.annotation.Service;
import org.checkerframework.checker.units.qual.A;
import org.nustaq.serialization.annotations.AnonymousTransient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author TL
 * @created Date:2020/12/20 Time:16:09
 **/
@Service(interfaceClass = IGoodsQueryServcice.class)
@Component
public class IGoodsQueryServiceImpl implements IGoodsQueryServcice {
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    GoodsSortByPageConverter goodsSortByPageConverter;

    @Override
    public ShowGoodsByPageResponse showGoodsSortByPage(ShowGoodsByPageRequest request) {
        System.out.println("I'm in?");
        Integer page = request.getPage();
        BigDecimal priceGt = request.getPriceGt();
        BigDecimal priceLte = request.getPriceLte();
        Integer size = request.getSize();
        Integer sort = request.getSort();
        String sortForQuery = null;
        PageHelper.startPage(page,size);
        Example example = new Example(Item.class);
        if(sort != null && sort == 1){
            sortForQuery = "asc";
            example.setOrderByClause("price" + " " + sortForQuery);
        }else if (sort != null && sort == -1){
            sortForQuery = "desc";
            example.setOrderByClause("price" + " " + sortForQuery);
        }else
            sortForQuery = null;
        Example.Criteria criteria = example.createCriteria();
        if(priceGt != null && priceLte != null){
            criteria.andBetween("price",priceGt,priceLte);
        }
        List<Item> items = itemMapper.selectByExample(example);
        PageInfo<Item> pageInfo =new PageInfo<>(items);
        long total = pageInfo.getTotal();
        List<GoodsSortDto> goodsSortDtos = goodsSortByPageConverter.items2DTO(items);
        ShowGoodsByPageResponse showGoodsByPageResponse = new ShowGoodsByPageResponse();
        showGoodsByPageResponse.setGoodsSortDtos(goodsSortDtos);
        showGoodsByPageResponse.setTotal((int) total);
        return showGoodsByPageResponse;
    }
}
